package org.jash.shop2111.net

import io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.jash.shop2111.entry.User
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

private val client by lazy {
    OkHttpClient.Builder()
        .addInterceptor {
            it.proceed(user?.let { u -> it.request().newBuilder().addHeader("token", u.token).build() } ?: it.request())
        }
        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
        .build()
}

val retrofit by lazy {
    Retrofit.Builder()
        .baseUrl("http://10.161.9.80:7012/")
        .client(client)
        .addConverterFactory(MyConverterFactory())
        .addCallAdapterFactory(RxJava3CallAdapterFactory.createWithScheduler(Schedulers.io()))
        .build()
}
inline fun <reified T> service(): T = retrofit.create(T::class.java)
var user:User? = null